package com.april.pattern.creational.singleton;

/**
 * @author April
 * @version V1.0.0
 * @date 2019/06/23 09:52
 * @description 双重检测锁
 */
public class LazyDoubleCheckSingleton {
    // 解决方式一：这里加上volatile关键字
    private volatile static LazyDoubleCheckSingleton lazyDoubleCheckSingleton = null;

    private LazyDoubleCheckSingleton() {

    }

    public static LazyDoubleCheckSingleton getInstance() {
        if (lazyDoubleCheckSingleton == null) {
            synchronized (LazyDoubleCheckSingleton.class) {
                if (lazyDoubleCheckSingleton == null) {
                    // 在单线程中，这里是允许进行指令重排序的
                    // 1.分配内存给这个对象
                    // 2.初始化对象
                    // 3.设置lazyDoubleCheckSingleton 指向刚分配的内存地址
                    // 这里的2和3是有可能指令重排的
                    lazyDoubleCheckSingleton = new LazyDoubleCheckSingleton();
                }
            }
        }

        return lazyDoubleCheckSingleton;
    }
}
